package cn.explink.dop.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.RowMapperResultSetExtractor;
import org.springframework.stereotype.Repository;

import cn.explink.distributor.framework.CommonCondition;
import cn.explink.dop.entity.vo.ConditionVO;
import cn.explink.dop.entity.vo.DistributeStrategyVO;
import cn.explink.dop.enums.pub.EnableEnum;
import cn.explink.dop.tools.Tools;
import cn.explink.eap.core.common.dao.impl.GenericBaseCommonDao;
import cn.explink.eap.core.util.StringUtil;

@Repository("distributeStrategyDao")
public class DistributeStrategyDao extends GenericBaseCommonDao<DistributeStrategyVO, String> {

	private static Logger logger = LoggerFactory.getLogger(DistributeStrategyDao.class);

	/**
	 * 按照实体获取分页数据
	 *
	 * @param baseInfo
	 *            查询实体
	 * @param pageNum
	 *            当前页
	 * @param pageSize
	 *            当前页记录条数
	 * @return 查询结果集
	 */
	public Map<String, Object> findByPage(final DistributeStrategyVO distributeStrategyVOParam, final int pageNum, final int pageSize) {
		StringBuffer sql = new StringBuffer("select * ").append("from bd_distribute_strategy where is_enable<>3");

		if (StringUtils.isNotBlank(distributeStrategyVOParam.getName())) {
			sql.append(" and name='").append(distributeStrategyVOParam.getName()).append("'");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("count", super.getJdbcTemplate().queryForLong(sql.toString().replace("*", "count(id)")));
		sql.append(" limit ").append((pageNum - 1) * pageSize).append(",").append(pageSize);
		List<Map<String, Object>> mapList = super.getJdbcTemplate().queryForList(sql.toString());
		List<DistributeStrategyVO> distributeStrategyVOList = new ArrayList<DistributeStrategyVO>();
		for (Map<String, Object> m : mapList) {
			DistributeStrategyVO d = (DistributeStrategyVO) Tools.convertMap(DistributeStrategyVO.class, m);
			distributeStrategyVOList.add(d);
		}
		for (DistributeStrategyVO distributeStrategyVO : distributeStrategyVOList) {
			List<ConditionVO> conditionVOList = this.getConditionListByDistributeStrategyId(distributeStrategyVO.getId());
			distributeStrategyVO.setConditionList(conditionVOList);
		}
		map.put("list", distributeStrategyVOList);
		return map;
	}
	//查询配单策略
	public DistributeStrategyVO getEnableDistributeStrategyList() {

		StringBuffer distributeStrategySql = new StringBuffer("select d.id,d.name,d.is_enable from bd_distribute_strategy d where d.is_enable=" + EnableEnum.Enable.getValue());

		List<DistributeStrategyVO> distributeStrategyVOList = super.getJdbcTemplate().query(distributeStrategySql.toString(),
				new RowMapperResultSetExtractor<DistributeStrategyVO>(new DistributeStrategyMapper()));//spring里rowmap的用法，把结果封装成对象
		if ((distributeStrategyVOList == null) || (distributeStrategyVOList.size() != 1)) {//每次只按一条策略来配单，否则提示
			DistributeStrategyDao.logger.error("启用的分单策略数量不为1");
			return new DistributeStrategyVO();
		} else {
			DistributeStrategyVO distributeStrategyVO = distributeStrategyVOList.get(0);
			List<ConditionVO> conditionVOList = this.getConditionListByDistributeStrategyId(distributeStrategyVO.getId());//获取这条策略的具体要求
			distributeStrategyVO.setConditionList(conditionVOList);
			return distributeStrategyVO;
		}
	}

	public List<DistributeStrategyVO> getDistributeStrategyList(DistributeStrategyVO distributeStrategyVOParam) {
		StringBuffer distributeStrategySql = new StringBuffer("select d.id,d.name,d.is_enable from bd_distribute_strategy d ");
		if (StringUtil.isNotEmpty(distributeStrategyVOParam.getName())) {
			distributeStrategySql.append(" where d.name='" + distributeStrategyVOParam.getName() + "'");
		}

		List<DistributeStrategyVO> distributeStrategyVOList = super.getJdbcTemplate().query(distributeStrategySql.toString(),
				new RowMapperResultSetExtractor<DistributeStrategyVO>(new DistributeStrategyMapper()));
		for (DistributeStrategyVO distributeStrategyVO : distributeStrategyVOList) {
			List<ConditionVO> conditionVOList = this.getConditionListByDistributeStrategyId(distributeStrategyVO.getId());
			distributeStrategyVO.setConditionList(conditionVOList);
		}
		return distributeStrategyVOList;
	}

	class DistributeStrategyMapper extends GenericBaseCommonDao<CommonCondition, String> implements RowMapper<DistributeStrategyVO> {
		@Override
		public DistributeStrategyVO mapRow(ResultSet rs, int index) throws SQLException {
			DistributeStrategyVO distributeStrategyVO = new DistributeStrategyVO();
			distributeStrategyVO.setId(rs.getString("id"));
			distributeStrategyVO.setName(rs.getString("name"));
			distributeStrategyVO.setIsEnable(rs.getInt("is_enable"));

			return distributeStrategyVO;
		}
	}

	private List<ConditionVO> getConditionListByDistributeStrategyId(String distributeStrategyId) {
		List<ConditionVO> conditionList = new ArrayList<ConditionVO>();

		StringBuffer sql = new StringBuffer("select * from bd_condition where distribute_strategy_id='" + distributeStrategyId + "'");

		conditionList = super.getJdbcTemplate().query(sql.toString(), new RowMapperResultSetExtractor<ConditionVO>(new ConditionRowMapper()));

		return conditionList;
	}

	class ConditionRowMapper implements RowMapper<ConditionVO> {
		@Override
		public ConditionVO mapRow(ResultSet rs, int index) throws SQLException {
			String className = rs.getString("class_name");
			ConditionVO condition = null;
			try {
				condition = (ConditionVO) Class.forName(className).newInstance();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
			if (condition != null) {
				condition.setId(rs.getString("id"));
				condition.setName(rs.getString("name"));
				condition.setPriority(rs.getInt("priority"));
				condition.setWeight(rs.getInt("weight"));
				//condition.setType(rs.getInt("type"));
			}
			return condition;
		}
	}

	/**
	 *
	 * @Title: stopdistributeStrategy
	 * @Description: 将其他的分单策略改为停用
	 * @author 孟凡岭
	 * @param @param id
	 * @return void 返回类型
	 * @throws
	 */
	public void stopdistributeStrategy(String id) {
		// TODO Auto-generated method stub
		String sql = "update bd_distribute_strategy set is_enable=2 where id<>?";
		this.getJdbcTemplate().update(sql, id);
	}

	/**
	 *
	 * @Title: stop
	 * @Description: 停用策略
	 * @author 孟凡岭
	 * @param @param idsList
	 * @return void 返回类型
	 * @throws
	 */
	public void stop(final List<String> idsList) {
		// TODO Auto-generated method stub
		String sql = "update bd_distribute_strategy set is_enable=2 where id=?";
		this.getJdbcTemplate().batchUpdate(sql, new BatchPreparedStatementSetter() {

			@Override
			public void setValues(PreparedStatement ps, int i) throws SQLException {
				// TODO Auto-generated method stub
				ps.setString(1, idsList.get(i));
			}

			@Override
			public int getBatchSize() {
				// TODO Auto-generated method stub
				return idsList.size();
			}
		});
	}

	/**
	 *
	 * @Title: open
	 * @Description: 启用策略，并将其他策略设为停用
	 * @author 孟凡岭
	 * @param @param id
	 * @return void 返回类型
	 * @throws
	 */
	public void open(String id) {
		// TODO Auto-generated method stub
		String sql = "update bd_distribute_strategy set is_enable=1 where id=?";
		this.getJdbcTemplate().update(sql, id);
		this.stopdistributeStrategy(id);
	}

	/**
	 *
	 * @Title: deleteDis
	 * @Description: 删除策略
	 * @author 孟凡岭
	 * @param @param idsList
	 * @return void 返回类型
	 * @throws
	 */
	public void deleteDis(final List<String> idsList) {
		// TODO Auto-generated method stub
		String sql = "update bd_distribute_strategy set is_enable=3 where id=?";
		this.getJdbcTemplate().batchUpdate(sql, new BatchPreparedStatementSetter() {

			@Override
			public void setValues(PreparedStatement ps, int i) throws SQLException {
				// TODO Auto-generated method stub
				ps.setString(1, idsList.get(i));
			}

			@Override
			public int getBatchSize() {
				// TODO Auto-generated method stub
				return idsList.size();
			}
		});
	}

}
